package client_AutoTag;


import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Iterator;

import tagsFilesClientDataBase.ClientFile;
import tagsFilesClientDataBase.TagFilesDB;;

/**
 * loading dynamic File Labeler class 
 * @author Orit and Yoav
 *
 */

public class LoadingClass {
	
	String plugInPath = new String(); //path of the plug-in that we get from user.  
	File libClass;
	String nameClass;
	TagFilesDB clientDB = TagFilesDB.getInstance();
	
	/**
	 * c'tor
	 * @param plugInPath the path of the plugin 
	 */
	public LoadingClass(String plugInPath) {  
		this.plugInPath = plugInPath;
		
		//plug in path have to include the package client_AutoTag 
		libClass = new File(plugInPath).getParentFile().getParentFile();
		
		//the name of the class (without the suffix ".class")
		nameClass = plugInPath.substring(plugInPath.lastIndexOf('\\')+1,plugInPath.lastIndexOf(".class"));		
	}
	
	/**
	 * default c'tor
	 */
	public LoadingClass() {
	}

	public void setPlugInPath(String plugInPath) { //set path from user.
		this.plugInPath = plugInPath;

		//plug in path have to include the package client_AutoTag 
		libClass = new File(plugInPath).getParentFile().getParentFile();
		
		//the name of the class (without the suffix ".class")
		nameClass = plugInPath.substring(plugInPath.lastIndexOf('\\')+1,plugInPath.lastIndexOf(".class"));		
	}
	
	/**
	 * implements user tag method 
	 */
	public void dynamicClassLoading(String file){	
		
		try {
		    // Convert File to a URL
		    URL url = libClass.toURI().toURL();      
		    URL[] urls = new URL[]{url};

		    // Create a new class loader with the directory
		    ClassLoader cl = new URLClassLoader(urls);	   
		    Class cls = cl.loadClass("client_AutoTag." + nameClass);
		    
		    FileLabeler fl=(FileLabeler) cls.newInstance();
		    clientDB.addTagMethodToDB(plugInPath);
		    if (file!=null) {//if we have the specific file
		    	labelFile(fl,file);
		    }
		    else			//add the plug-ins to all the files
		    	labelFiles(fl);
		    	
		} catch (MalformedURLException e) { 
		} catch (ClassNotFoundException e) { 
		} catch (InstantiationException e) {
		} catch (IllegalAccessException e) {
		}	
	}
	
	//label file with a specific path
	private void labelFile (FileLabeler fl,String file){
    	String labels[]=fl.label(new File(file));
    	for(String l : labels){  	//add all the labels to DB
    		clientDB.addTagToDB(l,file);
    	}		
	}
	
	
	//if we dont have the specific file label all the files in the Data base
	private void labelFiles(FileLabeler fl) throws InstantiationException, IllegalAccessException {	
	    Iterator<String> it=clientDB.getFileList().iterator();
	    while (it.hasNext()){ 		//for each file in the Data Base get it's labels  
	    	String file=it.next();
	    	labelFile(fl,file);
	    }	
	}

}